import {getYMD,getNowFormatDate,getDay,formatGMTDate,sortBy,toPercent} from '../../../../assets/js/util.js' 

import echarts from 'echarts'

export default{
  data() {
    return{
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        }
      },
      // 默认参数 和 URL
      SRC: '',
      DP: {
        p: '',
        f: '',
        uid: ''
      },
      prop: '',
      order: '',      
      loading: false,
      searchable: false,
      realLoadShow: true,
      title:'任务分析',
      xlsxTitle:'',
      ruleForm :{
        nowDate:'',
        platForm: '全平台',
        channel: '全渠道',
        tasktU: '全任务名称',
        tasktT: '全任务类型',
        server:'全区服'
      },
      tableHead1:[{"prop":"dateStr","label":"时间"},{"prop":"taskType","label":"任务类型"},{"prop":"taskId","label":"任务id"},{"prop":"taskName","label":"任务名称"},{"prop":"playUserNum","label":"参与角色数"},{"prop":"playTimes","label":"参与次数"},{"prop":"okRadio","label":"成功率"},{"prop":"avgPlayTimes","label":"人均次数"},{"prop":"avgTime","label":"平均完成时间(m)"}],
      
      tableData1P:[],
      tableData1: [],
      tableData2P:[],
      tableData2: [],
      tableData3: [],
      tableData3P: [],
      tableData4: [],
      tableData4P: [],

      page1:{
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        dataTotal: 0,
        currentPage: 1,
      },
      page2:{
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        dataTotal: 0,
        currentPage: 1,
      },
      page3:{
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        dataTotal: 0,
        currentPage: 1,
      },
      page4:{
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        dataTotal: 0,
        currentPage: 1,
      },
      // 全服
      servers:[],
      serNum:0,
      // 平台
      platForms:[],
      platNum:0,
      // 渠道名称
      channels:[],
      chanNum:0,
      // 任务类型
      tasktTs:[],
      tasktTNum:-99999,
      // 任务名称
      tasktUs:[],
      tasktUNum:-99999,
    }
  }, 
computed:{
		// xlsx(){
		//   return this.title+'.xlsx'
		// }
	},
  methods: {
            // 表格下载
    excel(tableIndex,sheet) {
      this.xlsxTitle = sheet+"-"+this.ruleForm.nowDate;
      this.downloadExl(this["tableHead1"],this["tableData"+tableIndex+"P"],this.xlsxTitle,sheet);
    },
    // 通用 成功 与 失败
		successFun(data) {
			this.$message({
				message: data,
				type: 'success'
			});
		},
		errorFun(data) {
			this.$message.error(data);
		},
    dateChange(val){
      if(val){
        var val = val.split(" ");
        this.sday = val[0];
        this.eday = val[2];
      }
    },
    nowChange(val){
      this.ruleForm.nowDate = val
    },
    tasktTChange(o){
      // 任务类型
      this.tasktTNum = o;
			this.apiAjax1('taskType='+o,'updateTaskType')
    },
    tasktUChange(o){
      // 任务名称
      this.tasktUNum = o;
      console.log(o)
			this.apiAjax1('taskName='+o,'updateTaskName')
    },
    platChange(o){
      // 平台
			this.platNum = o;
			this.apiAjax1('platform='+o,'updatePlatform')
    },
    channelChange(o){
      // 渠道
			this.chanNum = o;
			this.apiAjax1('channel='+o,'updateChannel')
    },
    serverChange(o){
      // 服务
			this.serNum = o;
			this.apiAjax1('server='+o,'updateServer')
    },
    loads() {
      this.loading = !this.loading; //加载中
      this.searchable = !this.searchable; //查询按钮不可用
    },
    handleSizeChange1(val) {
      this.page1.pageSize = val;
      this.tableData1P = sortBy(this.tableData1P,this.prop,this.order);
      this.page1.dataTotal = this.tableData1P.length;
      this.tableData1 = this.tableData1P.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
    },
    handleCurrentChange1(val) {
      this.page1.currentPage = val;
      this.tableData1P = sortBy(this.tableData1P,this.prop,this.order);
      this.page1.dataTotal = this.tableData1P.length;
      this.tableData1 = this.tableData1P.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
    },
    handleSizeChange2(val) {
      this.page2.pageSize = val;
      this.tableData2P = sortBy(this.tableData2P,this.prop,this.order);
      this.page2.dataTotal = this.tableData2P.length;
      this.tableData2 = this.tableData2P.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
    },
    handleCurrentChange2(val) {
      this.page2.currentPage = val;
      this.tableData2P = sortBy(this.tableData2P,this.prop,this.order);
      this.page2.dataTotal = this.tableData2P.length;
      this.tableData2 = this.tableData2P.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
    },
    handleSizeChange3(val) {
      this.page3.pageSize = val;
      this.tableData3P = sortBy(this.tableData3P,this.prop,this.order);
      this.page3.dataTotal = this.tableData3P.length;
      this.tableData3 = this.tableData3P.slice((this.page3.currentPage-1)*(this.page3.pageSize),this.page3.currentPage*this.page3.pageSize);
    },
    handleCurrentChange3(val) {
      this.page3.currentPage = val;
      this.tableData3P = sortBy(this.tableData3P,this.prop,this.order);
      this.page3.dataTotal = this.tableData3P.length;
      this.tableData3 = this.tableData3P.slice((this.page3.currentPage-1)*(this.page3.pageSize),this.page3.currentPage*this.page3.pageSize);
    },
    handleSizeChange4(val) {
      this.page4.pageSize = val;
      this.tableData4P = sortBy(this.tableData4P,this.prop,this.order);
      this.page4.dataTotal = this.tableData4P.length;
      this.tableData4 = this.tableData4P.slice((this.page4.currentPage-1)*(this.page4.pageSize),this.page4.currentPage*this.page4.pageSize);
    },
    handleCurrentChange4(val) {
      this.page4.currentPage = val;
      this.tableData4P = sortBy(this.tableData4P,this.prop,this.order);
      this.page4.dataTotal = this.tableData4P.length;
      this.tableData4 = this.tableData4P.slice((this.page4.currentPage-1)*(this.page4.pageSize),this.page4.currentPage*this.page4.pageSize);
    },         
    edit (){

    },
    handleDelete (){

    },
    // arrTojs
    getArrJson(arr){
      var arrNew = [];
      for(var i=0;i<arr.length;i++){
        var obj ={};
        obj.id = arr[i];
        obj.agentName = arr[i];
        arrNew.push(obj);
      }
      return arrNew;
    },
    getJsonarr(objarr){
      var arrNew = [];
      Object.keys(objarr).forEach(function(key){
          var obj = {}
          obj.id = key;
          obj.num = objarr[key];
          arrNew.push(obj)
      })
      return arrNew;
  },
  sortBy1(obj){
      return obj.sort(function(a,b){
          return parseInt(a['num']) - parseInt(b['num'])
      })
  },
    // 获取选择信息
    getData(){
      this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=initParam`,{
        params: {'ps':""}
      }).then(function(res){
        var data =  JSON.parse(JSON.parse(res.body));
       // console.log(data)
        if(data.res == "0"){
           this.platForms = this.sortBy1(this.getJsonarr(data.platformItmes));
           this.tasktUs = this.sortBy1(this.getJsonarr(data.uiTaskNameItmes));
           this.tasktTs = this.sortBy1(this.getJsonarr(data.taskTypeItmes));
           this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));
           this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));  
          //console.log(servers)
        }else{
          this.errorFun(data['msg'])
        }
      }).catch(function(res){
        console.log(res)
      })
    },
    search(){
      this.loads();
      this.apiAjax()
    },
    apiAjax1(keyV,aDo){
			this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=${aDo}`,{
        params: {'ps':keyV}
      }).then(function(res){
        var data =  JSON.parse(JSON.parse(res.body));
				if(data.res == "0"){
					if(aDo == 'updateServer'){
						this.platForms =this.sortBy1(this.getJsonarr(data.platformItmes));
						this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));
					}else if(aDo == 'updateChannel'){
						this.platForms =this.sortBy1(this.getJsonarr(data.platformItmes));
						this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));
					}else if(aDo == 'updatePlatform'){
						this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));						
						this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));
					}else if(aDo == 'updateTaskName'){
            this.tasktTs = this.sortBy1(this.getJsonarr(data.taskType));						
					}else if(aDo == 'updateTaskType'){
						this.tasktUs = this.sortBy1(this.getJsonarr(data.uiTaskNameItmes));
					}			
        }else{
          this.errorFun(data['msg'])
        }
      }).catch(function(res){})
		},
    apiAjax(){
      this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`,{
        params: {'ps':`dsearch=${this.ruleForm.nowDate}&platform=${this.platNum}&server=${this.serNum}&taskType=${this.tasktTNum}&channel=${this.chanNum}&taskName=${this.tasktUNum}`}
      }).then(function(res){
        
        var data = JSON.parse(JSON.parse(res.body).replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
        // console.log(data)
        if(parseInt(data['res']) === 0){
          this.loads();
          
          this.tableData1P = data.activeUserTaskCompletedsTran;
          for(var i = 0;i<this.tableData1P.length;i++){
            this.tableData1P[i].okRadio =  toPercent(this.tableData1P[i].okRadio)
          }
          this.page1.dataTotal = this.tableData1P.length;
          //this.tableData1P = sortBy(this.tableData1P,this.prop,this.order);
          this.tableData1 = this.tableData1P.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);

          this.tableData2P = data.newUserTaskCompletedsTran;
          for(var i = 0;i<this.tableData2P.length;i++){
            this.tableData2P[i].okRadio =  toPercent(this.tableData2P[i].okRadio)
          }
          this.page2.dataTotal = this.tableData2P.length;
         // this.tableData2P = sortBy(this.tableData2P,this.prop,this.order);
          this.tableData2 = this.tableData2P.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);


          this.tableData3P = data.activeUserTaskCompleteds;
          for(var i = 0;i<this.tableData3P.length;i++){
            this.tableData3P[i].okRadio =  toPercent(this.tableData3P[i].okRadio)
          }
          this.page3.dataTotal = this.tableData3P.length;
          //this.tableData3P = sortBy(this.tableData3P,this.prop,this.order);
          this.tableData3 = this.tableData3P.slice((this.page3.currentPage-1)*(this.page3.pageSize),this.page3.currentPage*this.page3.pageSize);


          this.tableData4P = data.newUserTaskCompleteds;
          for(var i = 0;i<this.tableData4P.length;i++){
            this.tableData4P[i].okRadio =  toPercent(this.tableData4P[i].okRadio)
          }
          this.page4.dataTotal = this.tableData4P.length;
         // this.tableData4P = sortBy(this.tableData4P,this.prop,this.order);
          this.tableData4 = this.tableData4P.slice((this.page4.currentPage-1)*(this.page4.pageSize),this.page4.currentPage*this.page4.pageSize);

          this.echartsData(data)
        }else{
          this.errorFun(data['msg'])
        }
      }).catch(function(res){})
    },
    sortChage1({ column, prop, order }){
      this.prop = prop;
      this.order = order;
      if(this.tableData1P.slice().length>0){
        this.tableData1All = this.tableData1P.slice();
        this.tableData1All = sortBy(this.tableData1All,this.prop,this.order);
        this.page1.currentPage = 1;
        this.tableData1 = [];
        this.tableData1 =this.tableData1All.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
        this.page1.dataTotal = this.tableData1All.length;
      }      
    },
    sortChage2({ column, prop, order }){
      this.prop = prop;
      this.order = order;
      if(this.tableData2P.slice().length>0){
        this.tableData2All = this.tableData2P.slice();
        this.tableData2All = sortBy(this.tableData2All,this.prop,this.order);
        this.page2.currentPage = 1;
        this.tableData2 = [];
        this.tableData2 =this.tableData2All.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
        this.page2.dataTotal = this.tableData2All.length;
      }     
    },
    sortChage3({ column, prop, order }){
      this.prop = prop;
      this.order = order;
      if(this.tableData3P.slice().length>0){
        this.tableData3All = this.tableData3P.slice();
        this.tableData3All = sortBy(this.tableData3All,this.prop,this.order);
        this.page3.currentPage = 1;
        this.tableData3 = [];
        this.tableData3 =this.tableData3All.slice((this.page3.currentPage-1)*(this.page3.pageSize),this.page3.currentPage*this.page3.pageSize);
        this.page3.dataTotal = this.tableData3All.length;
      }     
    },
    sortChage4({ column, prop, order }){
      this.prop = prop;
      this.order = order;
      if(this.tableData4P.slice().length>0){
        this.tableData4All = this.tableData4P.slice();
        this.tableData4All = sortBy(this.tableData4All,this.prop,this.order);
        this.page4.currentPage = 1;
        this.tableData4 = [];
        this.tableData4 =this.tableData4All.slice((this.page4.currentPage-1)*(this.page4.pageSize),this.page4.currentPage*this.page4.pageSize);
        this.page4.dataTotal = this.tableData4All.length;
      }    
    },
    //初始化
		// 设置图表初始化宽度
		chartsWidth (el){
			if(document.getElementById(el)!==null){
				document.getElementById(el).style.width = window.innerWidth-272+"px";
			}
		},
		_init() {
			var arr = ['realTimeData','realTimeData2'];
			for(var x=0; x<arr.length;x++){
				this.chartsWidth(arr[x]);
				this[arr[x]+'Chart'] = echarts.init(document.getElementById(arr[x]));
			}
			window.addEventListener('resize', function() {
				var resizeArr = ['realTimeDataChart','realTimeData2Chart']
				for(var j in resizeArr){
					this[resizeArr[j]].resize();
				}
			}.bind(this))
    },
    // 获取表数据
		echartsData(d) {
			if(d.activeUserTaskCompletedChartTran === undefined){
				var data = {
          columnkeys:[]
        }
			}else{
        var data = d.activeUserTaskCompletedChartTran['jsonStr'];
        this.realLoadShow = false;
      }
			this.realTimeDataChart.setOption({
        title: {
            text: ""
        },
        tooltip: {
          trigger: 'item',
          formatter : function (params) {
              return params.name+'<br>转化率：'+toPercent(params.value)
          }
        },
        legend: {
            data: ["转化率"]
        },
        grid:{
          left:'4%',
          right:'2%',
          bottom:'16%'
        },
        xAxis: [
            {
                type: "category",
                splitLine: {show: false},
                data: data.columnkeys
            }
        ],
        yAxis: [
          {
              type: "value",
              axisLabel: {
                show: true,  
                interval: 'auto',  
                formatter: function(val){
                  val = toPercent(val);
                  return val
                }
              }
          }
        ],
        toolbox: {
            show : true,
            feature : {
                mark : {show: true},
                dataView : {show: true, readOnly: false},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        dataZoom: {
          show: true,
          start : 0
        },
        calculable: true,
        series: [
            {
                name: "转化率",
                type: "line",
                showAllSymbol: true,
                data: data.data[0],
                itemStyle : {  
                    normal : {  
                        lineStyle:{  
                            color:'#2f7ed8'  
                        },
                        color:'#2f7ed8',  
                    }  
                }

            }
        ]
      });
			if(d.newUserTaskCompletedChartTran === undefined){
				var data = {
          columnkeys:[]
        }
			}else{
        var data = d.newUserTaskCompletedChartTran['jsonStr'];
        this.realLoadShow = false;
			}
			this.realTimeData2Chart.setOption({
				title: {
            text: ""
        },
        tooltip: {
          trigger: 'item',
          formatter : function (params) {
              return params.name+'<br>转化率：'+toPercent(params.value)
          }
        },
        legend: {
            data: ["转化率"]
        },
        grid:{
          left:'4%',
          right:'2%',
          bottom:'16%'
        },
        xAxis: [
            {
                type: "category",
                splitLine: {show: false},
                data: data.columnkeys
            }
        ],
        yAxis: [
          {
              type: "value",
              axisLabel: {
                show: true,  
                interval: 'auto',  
                formatter: function(val){
                  val = toPercent(val);
                  return val
                }
              }
          }
        ],
        toolbox: {
            show : true,
            feature : {
                mark : {show: true},
                dataView : {show: true, readOnly: false},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        dataZoom: {
          show: true,
          start : 0
        },
        calculable: true,
        series: [
            {
                name: "转化率",
                type: "line",
                showAllSymbol: true,
                data: data.data[0],
                itemStyle : {  
                    normal : {  
                        lineStyle:{  
                            color:'#2f7ed8'  
                        },
                        color:'#2f7ed8',  
                    }  
                }

            }
        ]
			});				
		},
  },  
  mounted() {
    // 初始化URL
    this.SRC = this.$store.getters.src;
    this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
    this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
    this.DP.uid = localStorage.getItem('ZULONGBIUSERID');
    this.ruleForm.nowDate = formatGMTDate(new Date(new Date().getTime() - 1000*60*60*24*1),true,true);
    this.getData();
    this.search();
    this._init();

  }
}